package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.mysql.jdbc.Connection;
import lombok.SneakyThrows;
import model.UserInfo;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;
import util.SessionUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.PreparedStatement;

/**
 * @author shkstart
 * 修改文章
 * @create 2023-01-16-12:04
 */
@WebServlet("/upart")
public class UpdateArticleServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String msg = "未知的参数 updatearticle";
        int data = 0;

        //登录权限校验
        UserInfo userInfo = SessionUtils.getLoginUser(req);
        if(userInfo!=null){
            //1.接收参数进行非空校验
            String title = req.getParameter("title");
            String context = req.getParameter("context");
            String aidstr = req.getParameter("aid");
            if(!StrUtil.isBlank(title)&&!StrUtil.isBlank(context)&&!StrUtil.isBlank(aidstr)){
                int aid = Integer.valueOf(aidstr);
                if(aid>0){
                    //2.对数据库进行操作
                    //2.1得到connect
                    Connection connection = DBUtils.getConnection();
                    //2.2拼接sql得到执行器
                    String sql = "update article set title=?,context=? where aid=? and uid = ?;";
                    //2.3执行sql,得到结果
                    PreparedStatement statement = connection.prepareStatement(sql);
                    statement.setString(1,title);
                    statement.setString(2,context);
                    statement.setInt(3,aid);
                    statement.setInt(4,userInfo.getUid());
                    data = statement.executeUpdate();
                    //2.4关闭连接
                    DBUtils.close(null,statement,connection);
                    msg = "成功抵达updatearticle";
                }else {
                    msg = "aid有问题";
                }



            }else {
                msg = "参数传递错误";
            }
        }else {
            msg = "当前用户未登录";
        }


        //3.将结果返回给前端
        resp.setContentType(AppVar.RESP_JSON_UTF8);
        resp.getWriter().println(
                JSONUtil.toJsonStr(
                        ResultUtils.toResult(200,data,msg)
                )
        );
    }
}
